package org.budo.mybatis.dao.factory;

import org.apache.ibatis.session.SqlSessionFactory;
import org.budo.mybatis.dao.MybatisDao;
import org.budo.mybatis.dao.impl.MybatisDaoImpl;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.FactoryBean;

import lombok.Getter;
import lombok.Setter;

/**
 * @author limingwei
 */
@Getter
@Setter
public class MybatisDaoFactory implements FactoryBean<MybatisDao> {
    private static final Logger log = Slf4j.getLogger();

    private MybatisDaoImpl mybatisDao = null;

    private SqlSessionFactory sqlSessionFactory;

    public MybatisDao getObject() throws Exception {
        if (null == this.mybatisDao) {
            synchronized (MybatisDaoFactory.class) {
                if (null == this.mybatisDao) {
                    this.mybatisDao = this.initMybatisDao();
                }
            }
        }
        return this.mybatisDao;
    }

    private MybatisDaoImpl initMybatisDao() {
        SqlSessionFactory sqlSessionFactory = this.getSqlSessionFactory();

        MybatisDaoImpl mybatisDao = new MybatisDaoImpl();
        mybatisDao.setSqlSessionFactory(sqlSessionFactory);

        log.info("initMybatisDao, mybatisDao=" + mybatisDao + ", sqlSessionFactory=" + sqlSessionFactory);
        return mybatisDao;
    }

    public Class<?> getObjectType() {
        return MybatisDao.class;
    }

    public boolean isSingleton() {
        return true;
    }
}